//
//  HomeViewModel.m
//  GLGW_Shoping
//
//  Created by yang on 2018/11/8.
//  Copyright © 2018年 yang. All rights reserved.
//

#import "HomeViewModel.h"
#import "BaseTableViewCell.h"
#import "HomeListHeaderView.h"
#import "HomeNewCycleHeaderView.h"
#import "HomeHeaderView.h"
#import "HomeEightSelectTableViewCell.h"
#import "HomeFourSelectTableViewCell.h"
#import "HomeDrawLineTableViewHeaderFooterView.h"
#import "HomeDrawLineTableViewCell.h"
#import "HomePageMenuTableViewHeaderFooterView.h"
#import "NoDataFootTableViewHeaderFooterView.h"
#import "SearchGoodsTableViewCell.h"
#import "SearchStoreTableViewCell.h"

#import "HomeFoundSotreTableViewCell.h"
#import "HomeGoodsRecommendTableViewCell.h"
#import "HomeHotOrderTableViewCell.h"
#import "HomeHotPictureTableViewCell.h"
#import "HomePickerView.h"
//model
#import "HomecategoryproductinfosModel.h"
#import "HomeCategoryModel.h"
#import "HomeFreemanagerpurchaseinfosModel.h"

@interface HomeViewModel ()<UITableViewDelegate,UITableViewDataSource>{
//    ;//优质商品推荐
    
    NSInteger isDidEndScrollItem;
}
@property(nonatomic,strong) NSMutableArray * cartModelArr;//优质商品
@property(nonatomic,strong) NSMutableArray * cartArr;//种类

@property(nonatomic,strong) NSMutableArray * storeModelArr;//发现店铺
@property(nonatomic,strong) NSMutableArray * freemanagerpurchaseinfosArr;//求购


@property (nonatomic,strong) UITableView * homeTableView;
@end
@implementation HomeViewModel

-(instancetype)initWithViewToViewModel:(UIView *)superView{
    if (self = [super init]) {
        isDidEndScrollItem = 0;
        self.cartModelArr = [NSMutableArray arrayWithCapacity:0];
        self.cartArr = [NSMutableArray arrayWithCapacity:0];
        self.storeModelArr = [NSMutableArray arrayWithCapacity:0];
        self.freemanagerpurchaseinfosArr = [NSMutableArray arrayWithCapacity:0];
        CGFloat navHeight;
        if (iPhoneX) {
            navHeight = 171;
        }else{
            navHeight = 113;
        }
        self.homeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - navHeight) style:UITableViewStyleGrouped];
        self.homeTableView.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
        //在iOS 11Self-Sizing自动打开后，contentSize和contentOffset都可能发生改变。可以通过以下方式禁用  防止cell或者footView刷新或者重用的时候跳动
        self.homeTableView.estimatedRowHeight = 10;
        self.homeTableView.mj_header.automaticallyChangeAlpha = YES;//自动更改透明度
        self.homeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;//
        [self.homeTableView registerClass:[HomeListHeaderView class] forHeaderFooterViewReuseIdentifier:@"HomeListHeaderView"];
        [self.homeTableView registerClass:[HomeNewCycleHeaderView class] forHeaderFooterViewReuseIdentifier:@"HomeNewCycleHeaderView"];
        [self.homeTableView registerClass:[HomeDrawLineTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"HomeDrawLineTableViewHeaderFooterView"];
        [self.homeTableView registerClass:[HomePageMenuTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"HomePageMenuTableViewHeaderFooterView"];
        [self.homeTableView registerClass:[NoDataFootTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"NoDataFootTableViewHeaderFooterView"];
        self.homeTableView.showsVerticalScrollIndicator = NO;
        self.homeTableView.delegate = self;
        self.homeTableView.dataSource = self;
        self.homeTableView.tableHeaderView = [self createHeaderView];
        [superView addSubview:self.homeTableView];
        [self requestAllcompanData];
        //
    }
    return self;
}
#pragma mark ---- 数据请求
//h公共请求数据接口
-(void)requestAllcompanData{
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t searialQueue = dispatch_queue_create("com.public.www", DISPATCH_QUEUE_SERIAL);
    
    dispatch_group_enter(group);
    dispatch_group_async(group, searialQueue, ^{
        // 网络请求一//折线图的数据
        [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kPricepolygonchart] lodingView:nil lodingTextString:@"" isLoding:NO parameters:@{@"categoryCode":@"123"} success:^(id  _Nullable response) {
            dispatch_group_leave(group);
        } failure:^(NSError * _Nullable error) {
            dispatch_group_leave(group);
        }];
    });
    
    dispatch_group_enter(group);
    dispatch_group_async(group, searialQueue, ^{
        // 网络请求二//1.1.13.    钢铁头条
        [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kHomeSteelNews] lodingView:nil lodingTextString:@"" isLoding:NO parameters:@{} success:^(id  _Nullable response) {
            dispatch_group_leave(group);
        } failure:^(NSError * _Nullable error) {
            dispatch_group_leave(group);
        }];
    });
    //网络请求结束后，会进入这个方法，在这个方法中进行洁面的刷行
    dispatch_group_notify(group, searialQueue, ^{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                // 刷新UI
                DLog(@"剩于的接口");
                [self requestData];
            });
        });
    });
}


-(void)requestData{
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t searialQueue = dispatch_queue_create("com.private.www", DISPATCH_QUEUE_SERIAL);
    
    dispatch_group_enter(group);
    dispatch_group_async(group, searialQueue, ^{
        // 网络请求一//优质商品推荐
        NSString * requStr;
        if (self.accountType == AccountType_FreeManagers) {
            requStr = kHomeFreemanagercategoryproductinfos;
        }else{
            requStr = kHomecategoryproductinfos;
        }
        [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,requStr] lodingView:nil lodingTextString:@"" isLoding:NO parameters:@{} success:^(id  _Nullable response) {
            HomecategoryproductinfosModel * cartgoryModel = [HomecategoryproductinfosModel yy_modelWithJSON:response];
            if (cartgoryModel.code == 0) {
                [self.cartModelArr addObjectsFromArray:cartgoryModel.data.categoryProductInfos];
                [self.cartArr addObjectsFromArray:cartgoryModel.data.category];
            }
            dispatch_group_leave(group);
        } failure:^(NSError * _Nullable error) {
            dispatch_group_leave(group);
        }];
    });
    
    dispatch_group_enter(group);
    dispatch_group_async(group, searialQueue, ^{
        // 网络请求二//发现店铺
        [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kHomelevelshopinfos] lodingView:nil lodingTextString:@"" isLoding:NO parameters:@{@"flag":@(self.accountType +1)} success:^(id  _Nullable response) {
            HomeCategoryModel * storeModel = [HomeCategoryModel yy_modelWithJSON:response];
            if (storeModel.code == 0) {
                [self.storeModelArr addObjectsFromArray:storeModel.data];
            }
            dispatch_group_leave(group);
        } failure:^(NSError * _Nullable error) {
            dispatch_group_leave(group);
        }];
    });
    if (self.accountType == AccountType_FreeManagers) {
        dispatch_group_enter(group);
        dispatch_group_async(group, searialQueue, ^{
            // 网络请求三//1.1.8.    首页求购
            [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kHomefreemanagerpurchaseinfos] lodingView:nil lodingTextString:@"" isLoding:NO parameters:@{} success:^(id  _Nullable response) {
                HomeFreemanagerpurchaseinfosModel * freemanagerModel = [HomeFreemanagerpurchaseinfosModel yy_modelWithJSON:response];
                if (freemanagerModel.code == 0) {
                    [self.freemanagerpurchaseinfosArr addObjectsFromArray:freemanagerModel.data];
                }
                dispatch_group_leave(group);
            } failure:^(NSError * _Nullable error) {
                dispatch_group_leave(group);
            }];
        });
    }
    //所有网络请求结束后，会进入这个方法，在这个方法中进行洁面的刷行
    dispatch_group_notify(group, searialQueue, ^{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                // 刷新UI
                DLog(@"刷新ui");
                [self.homeTableView reloadData];
            });
        });
    });
    
}
//优质商品点击选择的时候需要修改
-(void)requestGoodsList:(NSInteger)categoryCode{
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kHomegoodproductinfos] lodingView:nil lodingTextString:@"" isLoding:YES parameters:@{@"categoryCode":@(categoryCode)} success:^(id  _Nullable response) {
        HomeCategoryModel * categarModel = [HomeCategoryModel yy_modelWithJSON:response];
        if (categarModel.code == 0) {
            [self.cartModelArr removeAllObjects];
            [self.cartModelArr addObjectsFromArray:categarModel.data];
            if (self.accountType == AccountType_FreeManagers) {
                NSIndexSet *indexSet=[[NSIndexSet alloc] initWithIndex:4];
                [self.homeTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            }else{
                NSIndexSet *indexSet=[[NSIndexSet alloc] initWithIndex:2];
                [self.homeTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            }
        }
    } failure:^(NSError * _Nullable error) {
        
    }];
}

#pragma mark =================== headerView ===================
-(UIView *)createHeaderView{
    HomeHeaderView * headerView = [[HomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, kHeightProportion_In_iPhoneTriploid(150))];
    return headerView;
}
#pragma mark =================== UITableViewDelegate ===================
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.accountType == AccountType_Ordinary) {
        return 4;
    }else{
        return 5;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger cellNum;
    switch (section) {
        case 2:{
            if (self.accountType == AccountType_FreeManagers) {
                cellNum = self.freemanagerpurchaseinfosArr.count;
            }else{
                cellNum = self.cartModelArr.count;
            }
        }
            break;
        case 3:{
            cellNum = self.storeModelArr.count;
        }
            break;
        case 4:{
            cellNum = self.cartModelArr.count;
        }
            break;
            
        default:
            cellNum = 1;
            break;
    }
    return cellNum;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat cellHeight;
    switch (indexPath.section) {
        case 0:{
            if (self.accountType == AccountType_Ordinary) {
                cellHeight = kHeightProportion_In_iPhoneTriploid(95);
            }else{
                cellHeight = kHeightProportion_In_iPhoneTriploid(182);
            }
        }
            break;
        case 1:{
            cellHeight = kHeightProportion_In_iPhoneTriploid(298);
        }
            break;
        case 2:{
            if (self.accountType == AccountType_Ordinary) {
                cellHeight = kHeightProportion_In_iPhoneTriploid(132);
            }else{
                cellHeight = UITableViewAutomaticDimension;
            }
        }
            break;
        case 3:{
            cellHeight = kHeightProportion_In_iPhoneTriploid(126);
        }
            break;
        case 4:{
            cellHeight = kHeightProportion_In_iPhoneTriploid(136);
        }
            break;
            
        default:
            cellHeight = kHeightProportion_In_iPhoneTriploid(0.01);
            break;
    }
    return cellHeight;
}

#pragma mark =================== UITableViewDelegate ===================
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BaseTableViewCell * cell;
    switch (indexPath.section) {
        case 0:{
            if (self.accountType == AccountType_Ordinary) {
                HomeFourSelectTableViewCell * cell_Four = [HomeFourSelectTableViewCell cellWithTableView:tableView];
                cell_Four.Block_FourAction = ^(GLGWButton * _Nonnull but) {
                    if (self.delegate && [self.delegate respondsToSelector:@selector(homeEightButAction:)]) {
                        [self.delegate homeEightButAction:but];
                    }
                };
                cell = cell_Four;
            }else{
                HomeEightSelectTableViewCell * cell_eight = [HomeEightSelectTableViewCell cellWithTableView:tableView];
                cell_eight.Block_StellJiSuanQi = ^(GLGWButton * _Nonnull s_but) {
                    if (self.delegate && [self.delegate respondsToSelector:@selector(homeEightButAction:)]) {
                        [self.delegate homeEightButAction:s_but];
                    }
                };
                cell = cell_eight;
            }
        }
            break;
        case 1:{
            HomeDrawLineTableViewCell * cell_draw = [HomeDrawLineTableViewCell cellWithTableView:tableView];
            cell = cell_draw;
        }
            break;
        case 2:{
            if (self.accountType == AccountType_Ordinary) {
                SearchGoodsTableViewCell * cell_Goods = [SearchGoodsTableViewCell cellWithTableView:tableView];
                cell_Goods.catInforModel = self.cartModelArr[indexPath.row];
                cell = cell_Goods;
            }else{
                HomeFreemanagerpurchaseinfosModel_Data * prcueModel = self.freemanagerpurchaseinfosArr[indexPath.row];
                if (prcueModel.type == 3) {
                    HomeHotPictureTableViewCell * cell_picture = [HomeHotPictureTableViewCell cellWithTableView:tableView];
                    cell = cell_picture;
                }else{
                    HomeHotOrderTableViewCell * cell_hot = [HomeHotOrderTableViewCell cellWithTableView:tableView];
                    if (indexPath.row == 1) {
                        cell_hot.isHider = YES;
                    }else{
                        cell_hot.isHider = NO;
                    }
                    cell_hot.freeDataModel = prcueModel;
                    cell = cell_hot;
                }
            }
        }
            break;
        case 3:{
            HomeFoundSotreTableViewCell * cell_Store = [HomeFoundSotreTableViewCell cellWithTableView:tableView];
            cell_Store.storeInforModel = self.storeModelArr[indexPath.row];
            cell = cell_Store;
        }
            break;
        case 4:{
            HomeGoodsRecommendTableViewCell * cell_recommend = [HomeGoodsRecommendTableViewCell cellWithTableView:tableView];
            cell_recommend.carteListmodel = self.cartModelArr[indexPath.row];
            cell = cell_recommend;
        }
            break;
            
        default:
            break;
    }

    return cell;
}
#pragma mark =================== sectionHeadre ===================
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView * headerView;
    switch (section) {
        case 0:{
            HomeNewCycleHeaderView *cycleHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HomeNewCycleHeaderView"];
            headerView = cycleHeaderView;
        }
            break;
        case 1:{
            HomeDrawLineTableViewHeaderFooterView * drawLineHeadreView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HomeDrawLineTableViewHeaderFooterView"];
            drawLineHeadreView.Block_DrawAgarn = ^(GLGWButton * _Nonnull d_but) {
                DLog(@"点击啦");
                if (d_but.tag == 150) {
                    HomePickerView * piceView = [[HomePickerView alloc] initWithPickerView:PickerViewType_Stell];
                }else{
                    HomePickerView * piceView = [[HomePickerView alloc] initWithPickerView:PickerViewType_Time];
                }
            };
            headerView = drawLineHeadreView;
        }
            break;
        case 2:{
            if (self.accountType == AccountType_Ordinary) {
                HomePageMenuTableViewHeaderFooterView * pageMernuHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HomePageMenuTableViewHeaderFooterView"];
                [pageMernuHeaderView pageEmuDataArr:self.cartArr theSelectIndex:isDidEndScrollItem];
                pageMernuHeaderView.Block_ChickNum = ^(NSInteger num) {
                    self->isDidEndScrollItem = num;
                    HomecategoryproductinfosModel_Category * catareModel = self.cartArr[num];
                    [self requestGoodsList:catareModel.categoryCode];
                };
                headerView = pageMernuHeaderView;
            }else{
                HomeListHeaderView *shopcartHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HomeListHeaderView"];
                shopcartHeaderView.titStr = @"热门求购单";
                headerView = shopcartHeaderView;
            }
            
        }
            break;
        case 3:{
            HomeListHeaderView *shopcartHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HomeListHeaderView"];
            shopcartHeaderView.titStr = @"发现店铺";
            headerView = shopcartHeaderView;
        }
            break;
        case 4:{
            HomePageMenuTableViewHeaderFooterView * pageMernuHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HomePageMenuTableViewHeaderFooterView"];
            [pageMernuHeaderView pageEmuDataArr:self.cartArr theSelectIndex:isDidEndScrollItem];
            pageMernuHeaderView.Block_ChickNum = ^(NSInteger num) {
                self->isDidEndScrollItem = num;
                HomecategoryproductinfosModel_Category * catareModel = self.cartArr[num];
                [self requestGoodsList:catareModel.categoryCode];
            };
            headerView = pageMernuHeaderView;
        }
            break;
            
        default:
            break;
    }
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    CGFloat headerHeight;
    switch (section) {
        case 0:{
            headerHeight = kHeightProportion_In_iPhoneTriploid(87);
        }
            break;
        case 1:{
            headerHeight = kHeightProportion_In_iPhoneTriploid(60);
        }
            break;
        case 2:{
            if (self.accountType == AccountType_Ordinary) {
                headerHeight = kHeightProportion_In_iPhoneTriploid(110);
            }else{
                headerHeight = kHeightProportion_In_iPhoneTriploid(75);
            }
        }
            break;
        case 3:{
            headerHeight = kHeightProportion_In_iPhoneTriploid(75);
        }
            break;
        case 4:{
            headerHeight = kHeightProportion_In_iPhoneTriploid(110);
        }
            break;
            
        default:
            headerHeight = kHeightProportion_In_iPhoneTriploid(0.01);
            break;
    }

    return headerHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    NoDataFootTableViewHeaderFooterView * footView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"NoDataFootTableViewHeaderFooterView"];
    return footView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
@end
